﻿namespace PowerSong.UserInterface
    {
    using System;
    using System.Windows;
    using System.Windows.Media;
    using PowerSong.SongDatabase;
    using PowerSong.UserInterface.Tasks;

    /// <summary>
    /// Interaction logic for ConfigurationWindow.xaml
    /// </summary>
    public partial class ConfigurePowerSongWindow : Window
        {

        public ConfigurePowerSongWindow()
            {

            InitializeComponent();
            this.DataContext = State.Settings;
            this.NoticeFont.AssociatedPreviewControl = NoticeFontPreviewTextBlock;

            // Show current settings
            this.NoticeTextColor.Brush = new SolidColorBrush(State.Settings.NoticeTextColour.ToColor());
            this.NoticeBackgroundColor.Brush = new SolidColorBrush(State.Settings.NoticeBackgroundColour.ToColor());

            // Show installed bible translations
            UpdateBibleList();

            // Set enabled state of controls
            UpdateEnabledControls();

            }

        private void UpdateBibleList()
            {
            BiblesListBox.Items.Clear();
            foreach (var translationName in BibleTranslationManager.GetTranslations())
                {
                BiblesListBox.Items.Add(translationName);
                }
            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            try
                {

                // Apply general settings
                State.Settings.PopupSongPreviews = this.PopupSongPreviewsCheckBox.IsChecked == true;
                State.Settings.EnableReporting = this.EnableReportingCheckBox.IsChecked == true;
                State.Settings.AutoCreateProjectionWindow = this.AutoCreateProjectionWindowCheckBox.IsChecked == true;

                // Apply notice settings
                State.Settings.NoticeDuration = int.Parse(NoticeDurationTextBox.Text);
                State.Settings.NoticeTimeToAppear = int.Parse(NoticeTimeToAppearTextBox.Text);
                State.Settings.NoticeTimeToDissappear = int.Parse(NoticeTimeToDissappearTextBox.Text);
                State.Settings.NoticeBackgroundColour = this.NoticeBackgroundColor.Color.ToUInt();
                State.Settings.NoticeTextColour = this.NoticeTextColor.Color.ToUInt();
                State.Settings.NoticeSpeed = double.Parse(NoticeSpeedTextBox.Text);
                State.Settings.NoticeFontName = NoticeFont.SelectedName;
                State.Settings.NoticeFontSize = NoticeFont.SelectedSize;
                State.Settings.NoticeFontStyle = NoticeFont.SelectedStyle;

                // Save the settings
                State.Settings.SaveChanges();

                // Close the window
                this.DialogResult = true;

                }
            catch (Exception ex)
                {
                Utilities.ShowErrorMessage("Could Not Apply Settings", ex.Message);
                }

            }

        private void SetActiveTranslationButton_Click(object sender, RoutedEventArgs e)
            {
            var selectedTranslation = (string)BiblesListBox.SelectedItem;
            if (selectedTranslation != null)
                {
                if (Utilities.Confirm("Set Active Translation", "Are you sure you want to set the selected bible translation as the active bible translation, which will be used when you search for chapters?"))
                    {
                    State.Settings.ActiveBibleTranslation = selectedTranslation;
                    State.ChangeBible(selectedTranslation);
                    UpdateBibleList();
                    UpdateEnabledControls();
                    }
                }
            }

        private void AddTranslationButton_Click(object sender, RoutedEventArgs e)
            {

            // Get the file name of the bible file
            var fileName = OpenFileControl.RequestFileName(FileFilters.Bible);
            if (!string.IsNullOrEmpty(fileName))
                {

                // Install the Bible translation
                var task = new InstallTranslationTask(fileName);
                ProgressWindow.Start(task);
                Utilities.ShowInformationMessage("Translation Installed", "The Bible Translation '" + fileName + "' has been installed!");

                // Was this the first installed bible translation?
                var installedTranslations = BibleTranslationManager.GetTranslations();
                if (installedTranslations.Length == 1)
                    {
                    State.Settings.ActiveBibleTranslation = installedTranslations[0];
                    State.ChangeBible(installedTranslations[0]);
                    State.Settings.SaveChanges();
                    Utilities.ShowInformationMessage("Active Translation Changed", "The active bible translation has been changed to '" + installedTranslations[0] + "'.");
                    }

                // Refresh visual state
                UpdateBibleList();
                UpdateEnabledControls();

                }

            }

        private void DeleteTranslationButton_Click(object sender, RoutedEventArgs e)
            {
            var selectedTranslation = (string)BiblesListBox.SelectedItem;
            if (selectedTranslation != null)
                {
                if (Utilities.Confirm("Confirm Delete", "Are you sure you wish to permanently delete the selected translation?"))
                    {

                    // Is this the default translation being deleted?
                    var defaultDeleted = State.Settings.ActiveBibleTranslation == selectedTranslation;

                    // Release the active bible translation if it is the one being deleted
                    if (defaultDeleted)
                        {
                        State.ChangeBible(null);
                        State.Settings.ActiveBibleTranslation = null;
                        }
                        
                    // Delete the translation
                    BibleTranslationManager.DeleteTranslation(selectedTranslation);

                    // Update default translation
                    if (defaultDeleted)
                        {
                        var translations = BibleTranslationManager.GetTranslations();
                        if (translations.Length > 0)
                            {
                            State.Settings.ActiveBibleTranslation = translations[0];
                            State.ChangeBible(translations[0]);
                            State.Settings.SaveChanges();
                            Utilities.ShowInformationMessage("Active Translation Changed", "The active bible translation has been changed to '" + translations[0] + "'.");
                            }                        
                        }

                    // Update visual state
                    UpdateBibleList();
                    UpdateEnabledControls();

                    }
                }
            }

        private void UpdateEnabledControls()
            {
            this.DeleteTranslationButton.IsEnabled = BiblesListBox.Items.Count > 0;
            this.SetActiveTranslationButton.IsEnabled = BiblesListBox.Items.Count > 0;
            }

        private void NoticeTextColor_BrushChanged(Brush brush)
            {
            NoticeFontPreviewTextBlock.Foreground = brush;
            }

        private void NoticeBackgroundColor_BrushChanged(Brush brush)
            {
            NoticeFontPreviewBorder.Background = brush;
            }

        }

    }
